﻿using Czj_VoteSys.Models;
using Czj_VoteSys.Models.Database;
using Czj_VoteSys.Models.Userlei;
using Czj_VoteSys.Service;
using Czj_VoteSys.Userlei;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Czj_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Czj_VoteSysContext _db;
        private readonly IJWTService _jwtService;
        public UserController(Czj_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }
        [HttpPost]
        public string Sign(SignRequest request)
        {
            //接口的具体实现
            //二次确认密码
            if (request.Password != request.Password2)
                return "两次输入不一致";

            //手机号不能重复
            if (_db.Users.Any(x => x.Email == request.Email))
                return "邮箱已存在";
            //100000到999999 6位数的随机字符串
            var salt = new Random().Next(100000, 999999).ToString();
            //                                 "123456"+"565644"
            //                                  即使密码相同 因为盐值是随机的 所以加密的结果是不一致的
            var md5 = MD5Helper.MD5Encrypt32(request.Password + salt);
            //添加一个新的用户
            var user = new User

            {
                Password = md5,
                Email = request.Email,
                Salt = salt
            };

            _db.Users.Add(user);
            //保存更改 增加 修改 删除
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        [HttpPost]
        public string Login(LoginRequest request)
        {
            //查询数据库手机号码为输入的手机号的用户
            var user = _db.Users.FirstOrDefault(x => x.Email == request.Email);
            if (user == null)
                return "用户不存在";

            //char 固定长度字符串char30
            //如果用户存在
            //"123456"                "123456             "
            var md5 = MD5Helper.MD5Encrypt32(request.Password + user.Salt);
            if (md5 != user.Password)
                return "输入的密码不正确";


            //创建token
            return _jwtService.CreateToken(user.Email, user.Password);
        }
    }
}
